// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  try {
    const { action } = event

    switch (action) {
      // 获取我的发布
      case 'getMyPublish':
        return await getMyPublish(event, wxContext)
      
      // 获取我的收藏
      case 'getMyFavorite':
        return await getMyFavorite(event, wxContext)
      
      // 添加浏览历史
      case 'addBrowseHistory':
        return await addBrowseHistory(event, wxContext)
      
      // 获取浏览历史
      case 'getBrowseHistory':
        return await getBrowseHistory(event, wxContext)
      
      // 清空浏览历史
      case 'clearBrowseHistory':
        return await clearBrowseHistory(event, wxContext)
      
      // 获取统计数据
      case 'getStatistics':
        return await getStatistics(event, wxContext)
      
      // 取消收藏
      case 'toggleFavorite':
        return await toggleFavorite(event, wxContext)
      
      // 检查收藏状态
      case 'checkFavoriteStatus':
        return await checkFavoriteStatus(event, wxContext)
      
      // 添加收藏
      case 'addFavorite':
        return await addFavorite(event, wxContext)
      
      default:
        return {
          code: -1,
          msg: '无效的action参数'
        }
    }
  } catch (err) {
    console.error(err)
    return {
      code: -1,
      msg: '服务器错误',
      error: err
    }
  }
}

/**
 * 获取我的发布
 */
async function getMyPublish(event, wxContext) {
  const { OPENID } = wxContext
  const { type, page = 1, pageSize = 20 } = event

  try {
    const skip = (page - 1) * pageSize
    let collection = type === 'goods' ? 'goods' : 'lost_found'

    // 获取列表
    const result = await db.collection(collection)
      .where({
        openid: OPENID
      })
      .orderBy('created_at', 'desc')
      .skip(skip)
      .limit(pageSize)
      .get()

    // 获取总数
    const countResult = await db.collection(collection)
      .where({
        openid: OPENID
      })
      .count()

    // 判断是否还有更多数据
    const hasMore = result.data.length >= pageSize

    return {
      code: 0,
      msg: '获取成功',
      data: {
        list: result.data,
        total: countResult.total,
        hasMore: hasMore
      }
    }
  } catch (err) {
    console.error('获取我的发布失败：', err)
    return {
      code: -1,
      msg: '获取失败',
      error: err
    }
  }
}

/**
 * 获取我的收藏
 */
async function getMyFavorite(event, wxContext) {
  const { OPENID } = wxContext
  const { item_type, page = 1, pageSize = 20 } = event

  try {
    const skip = (page - 1) * pageSize
    let where = {
      openid: OPENID
    }

    if (item_type) {
      where.item_type = item_type // 1-商品 2-失物招领
    }

    // 获取收藏记录
    const favorites = await db.collection('favorites')
      .where(where)
      .orderBy('created_at', 'desc')
      .skip(skip)
      .limit(pageSize)
      .get()

    // 获取总数
    const countResult = await db.collection('favorites')
      .where(where)
      .count()

    if (favorites.data.length === 0) {
      return {
        code: 0,
        msg: '获取成功',
        data: {
          list: [],
          total: 0,
          hasMore: false
        }
      }
    }

    // 获取详细信息
    const results = []
    const invalidFavorites = [] // 记录无效的收藏
    
    for (let favorite of favorites.data) {
      const collection = favorite.item_type === 1 ? 'goods' : 'lost_found'
      const idField = favorite.item_type === 1 ? 'goods_id' : 'lost_id'
      const dataField = favorite.item_type === 1 ? 'goods' : 'lost'
      
      try {
        const item = await db.collection(collection).doc(favorite.item_id).get()
        if (item.data) {
          results.push({
            _id: favorite._id,
            [idField]: favorite.item_id,
            [dataField]: item.data,
            created_at: favorite.created_at
          })
        } else {
          // 商品/失物不存在，记录为无效收藏
          invalidFavorites.push(favorite._id)
        }
      } catch (err) {
        console.error('获取收藏详情失败：', err)
        // 如果是因为商品不存在导致的错误，也记录为无效收藏
        invalidFavorites.push(favorite._id)
      }
    }
    
    // 自动清理无效的收藏记录
    if (invalidFavorites.length > 0) {
      try {
        for (let favoriteId of invalidFavorites) {
          await db.collection('favorites').doc(favoriteId).remove()
        }
        console.log('已自动清理', invalidFavorites.length, '条无效收藏记录')
      } catch (err) {
        console.error('清理无效收藏记录失败：', err)
      }
    }

    const hasMore = favorites.data.length >= pageSize

    // 重新统计有效的收藏总数（清理后的实际数量）
    const validTotal = countResult.total - invalidFavorites.length

    return {
      code: 0,
      msg: '获取成功',
      data: {
        list: results,
        total: validTotal, // 返回清理后的实际数量
        hasMore: hasMore
      }
    }
  } catch (err) {
    console.error('获取我的收藏失败：', err)
    return {
      code: -1,
      msg: '获取失败',
      error: err
    }
  }
}

/**
 * 添加浏览历史
 */
async function addBrowseHistory(event, wxContext) {
  const { OPENID } = wxContext
  const { item_type, item_id } = event

  try {
    await db.collection('browse_history').add({
      data: {
        openid: OPENID,
        item_type, // 1-商品 2-失物招领
        item_id,
        created_at: new Date()
      }
    })

    return {
      code: 0,
      msg: '添加成功'
    }
  } catch (err) {
    console.error('添加浏览历史失败：', err)
    return {
      code: -1,
      msg: '添加失败',
      error: err
    }
  }
}

/**
 * 获取浏览历史
 */
async function getBrowseHistory(event, wxContext) {
  const { OPENID } = wxContext
  const { page = 1, pageSize = 20 } = event

  try {
    const skip = (page - 1) * pageSize

    // 获取浏览历史记录
    const history = await db.collection('browse_history')
      .where({
        openid: OPENID
      })
      .orderBy('created_at', 'desc')
      .skip(skip)
      .limit(pageSize)
      .get()

    if (history.data.length === 0) {
      return {
        code: 0,
        msg: '获取成功',
        data: []
      }
    }

    // 获取详细信息（去重）
    const results = []
    const seen = new Set()

    for (let record of history.data) {
      const key = `${record.item_type}_${record.item_id}`
      if (seen.has(key)) continue
      seen.add(key)

      const collection = record.item_type === 1 ? 'goods' : 'lost_found'
      try {
        const item = await db.collection(collection).doc(record.item_id).get()
        if (item.data) {
          results.push({
            ...item.data,
            browse_time: record.created_at
          })
        }
      } catch (err) {
        console.error('获取浏览详情失败：', err)
      }
    }

    return {
      code: 0,
      msg: '获取成功',
      data: results
    }
  } catch (err) {
    console.error('获取浏览历史失败：', err)
    return {
      code: -1,
      msg: '获取失败',
      error: err
    }
  }
}

/**
 * 清空浏览历史
 */
async function clearBrowseHistory(event, wxContext) {
  const { OPENID } = wxContext

  try {
    await db.collection('browse_history')
      .where({
        openid: OPENID
      })
      .remove()

    return {
      code: 0,
      msg: '清空成功'
    }
  } catch (err) {
    console.error('清空浏览历史失败：', err)
    return {
      code: -1,
      msg: '清空失败',
      error: err
    }
  }
}

/**
 * 获取统计数据
 */
async function getStatistics(event, wxContext) {
  const { OPENID } = wxContext

  try {
    // 统计发布数量
    const goodsCount = await db.collection('goods')
      .where({ openid: OPENID })
      .count()

    const lostFoundCount = await db.collection('lost_found')
      .where({ openid: OPENID })
      .count()

    // 统计收藏数量
    const favoriteCount = await db.collection('favorites')
      .where({ openid: OPENID })
      .count()

    // 统计总浏览量
    const goodsResult = await db.collection('goods')
      .where({ openid: OPENID })
      .field({ view_count: true })
      .get()

    const lostFoundResult = await db.collection('lost_found')
      .where({ openid: OPENID })
      .field({ view_count: true })
      .get()

    let totalViews = 0
    goodsResult.data.forEach(item => {
      totalViews += item.view_count || 0
    })
    lostFoundResult.data.forEach(item => {
      totalViews += item.view_count || 0
    })

    return {
      code: 0,
      msg: '获取成功',
      data: {
        publishCount: goodsCount.total + lostFoundCount.total,
        goodsCount: goodsCount.total,
        lostFoundCount: lostFoundCount.total,
        favoriteCount: favoriteCount.total,
        totalViews: totalViews
      }
    }
  } catch (err) {
    console.error('获取统计数据失败：', err)
    return {
      code: -1,
      msg: '获取失败',
      error: err
    }
  }
}

/**
 * 取消收藏
 */
async function toggleFavorite(event, wxContext) {
  const { OPENID } = wxContext
  const { favorite_id } = event

  try {
    // 验证权限
    const favorite = await db.collection('favorites').doc(favorite_id).get()
    if (!favorite.data) {
      return {
        code: -1,
        msg: '收藏记录不存在'
      }
    }

    if (favorite.data.openid !== OPENID) {
      return {
        code: -1,
        msg: '无权限操作'
      }
    }

    // 删除收藏
    await db.collection('favorites').doc(favorite_id).remove()

    return {
      code: 0,
      msg: '取消收藏成功'
    }
  } catch (err) {
    console.error('取消收藏失败：', err)
    return {
      code: -1,
      msg: '操作失败',
      error: err
    }
  }
}

/**
 * 检查收藏状态
 */
async function checkFavoriteStatus(event, wxContext) {
  const { OPENID } = wxContext
  const { item_type, item_id } = event

  try {
    // 查询是否已收藏
    const result = await db.collection('favorites')
      .where({
        openid: OPENID,
        item_type: item_type,
        item_id: item_id
      })
      .get()

    return {
      code: 0,
      msg: '查询成功',
      data: {
        isFavorite: result.data.length > 0,
        favoriteId: result.data.length > 0 ? result.data[0]._id : null
      }
    }
  } catch (err) {
    console.error('检查收藏状态失败：', err)
    return {
      code: -1,
      msg: '查询失败',
      error: err
    }
  }
}

/**
 * 添加收藏
 */
async function addFavorite(event, wxContext) {
  const { OPENID } = wxContext
  const { item_type, item_id } = event

  try {
    // 先检查是否已经收藏过
    const existing = await db.collection('favorites')
      .where({
        openid: OPENID,
        item_type: item_type,
        item_id: item_id
      })
      .get()

    if (existing.data.length > 0) {
      return {
        code: -1,
        msg: '已经收藏过了'
      }
    }

    // 添加收藏记录
    const result = await db.collection('favorites').add({
      data: {
        openid: OPENID,
        item_type: item_type, // 1-商品 2-失物招领
        item_id: item_id,
        created_at: new Date()
      }
    })

    return {
      code: 0,
      msg: '收藏成功',
      data: {
        favoriteId: result._id
      }
    }
  } catch (err) {
    console.error('添加收藏失败：', err)
    return {
      code: -1,
      msg: '收藏失败',
      error: err
    }
  }
}

